const express = require("express");
const cors = require("cors");
const mysql = require("mysql");
const bodyParser = require('body-parser');
const app = express();

app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json({limit : "2100000kb"}))

const conn = mysql.createConnection({
	host: "yisurds-67a96e05201735.rds.ysydb1.com", 
	user: "67a96e052017353651:precharge_admin", 
    port: "3306",
	password: "Xlstl12345",
    database: "precharge",
    multipleStatements: true
});

conn.connect((error) =>{
    if (error) {
        console.error('连接失败：', error);
    } else {
        console.log('成功连接到数据库');
    }
});

//获取所有用户信息
app.get("/getAllUser", (req, res) => {
	conn.query('SELECT * FROM userinfo',(error, result) => {
		if (error) res.send({
            message: "error",
            status: 500,
        });
		res.send({
			message: "success",
			status: 200,
			data: result,
		});
	});
});


//获取单个用户信息
app.post("/getUserInfo", (req, res) => {
    const sql = "SELECT * FROM userinfo WHERE cardNumber = " + req.body.userCardNumber + ";"
	conn.query(sql,(error, result) => {
		if (error) res.send({
            message: "error",
            status: 500,
        });
		res.send({
			message: "success",
			status: 200,
			data: result,
		});
	});
});


//管理员登录
app.post("/adminLogin", (req, res) => {
	const sql = "SELECT * FROM admin WHERE adminAcc = ?";
	conn.query(sql, [req.body.adminAcc], (error, result) => {
		if (error) {
			res.send({
				message: error,
				status: 500,
			});
		} else if (result.length > 0 && result[0].adminPwd === req.body.adminPwd) {
			res.send({
				message: "success",
				status: 200,
				data: result[0].name,
			});
		} else {
			res.send({
				message: "用户名或密码错误",
				status: 401,
			});
		}
	});
});

//购买商品
app.post("/purchaseItems", (req, res) => {
	const { userinfo, cart, date, imageSrc } = req.body;
	let totalCost = 0;

	// 算出总价
	cart.forEach(item => {
		totalCost += item.price * item.quantity;
	});
	
	// 写入数据库
	const deductMoneySql = "UPDATE userinfo SET balance = balance - ? WHERE CardNumber = ?";
	conn.query(deductMoneySql, [totalCost, userinfo.cardNumber], (error, result) => {
		if (error) {
			return res.send({
				message: "error",
				status: 500,
			});
		}
		// 记录订单
		const insertOrderSql = "INSERT INTO `precharge`.`2024/02-shopHis` (`itemName`, `itemPrice`, `itemQuantity`, `consumer`, `consumeDate`, `consumerName`, `consumerPic`) VALUES ?";
		const values = cart.map(item => [item.name, item.price, item.quantity, userinfo.cardNumber, date, userinfo.userName, imageSrc]);
		conn.query(insertOrderSql, [values], (error) => {
			if (error) {
				return res.send({
					message: "error",
					status: 500,
				});
			}
			res.send({
				message: "success",
				status: 200,
			});
		});
	});
});


//查询某人的订单
app.post("/searchOnesOrder", (req, res) => {
	const sql = "SELECT * FROM `2024/02-shopHis` WHERE consumer = ?";
	conn.query(sql, [req.body.cardNumber], (error, result) => {
		if (error) {
			return res.send({
				message: "error",
				status: 500,
			});
		}
		res.send({
			message: "success",
			status: 200,
			data: result,
		});
	});
});


//按日期查询订单
app.post("/getOrdersByDate", (req, res) => {
	const sql = "SELECT itemName, itemPrice, itemQuantity, consumer, consumerName, consumeDate FROM `2024/02-shopHis` WHERE consumeDate = ?";
	conn.query(sql, [req.body.date], (error, result) => {
		if (error) {
			return res.send({
				message: "error",
				status: 500,
			});
		}
		res.send({
			message: "success",
			status: 200,
			data: result,
		});
	});
});


//充值
app.post("/recharge", (req, res) => {
	const checkUserSql = "SELECT * FROM userinfo WHERE cardNumber = ?";
	conn.query(checkUserSql, [req.body.cardNumber], (error, result) => {
		if (error) {
			return res.send({
				message: "error",
				status: 500,
			});
		}
		if (result.length === 0) {
			return res.send({
				message: "用户不存在",
				status: 404,
			});
		}
		const sql = "UPDATE userinfo SET balance = balance + ? WHERE cardNumber = ?";
		conn.query(sql, [req.body.rechargeAmount, req.body.cardNumber], (error) => {
			if (error) {
				return res.send({
					message: "error",
					status: 500,
				});
			}
			res.send({
				message: "success",
				status: 200,
			});
		});
	});
});

//创建用户
app.post("/createUser", (req, res) => {
	const checkUserSql = "SELECT * FROM userinfo WHERE cardNumber = ?";
	conn.query(checkUserSql, [req.body.userInfo.cardNumber], (error, result) => {
		if (error) {
			return res.send({
				message: "error",
				status: 500,
			});
		}
		if (result.length > 0) {
			return res.send({
				message: "用户已存在",
				status: 403,
			});
		}
		const sql = "INSERT INTO userinfo (cardNumber, userName, phoneNumber, balance) VALUES (?, ?, ?, ?)";
		conn.query(sql, [req.body.userInfo.cardNumber, req.body.userInfo.userName, req.body.userInfo.phoneNumber, req.body.userInfo.balance], (error) => {
			if (error) {
				console.log(error);
				return res.send({
					message: "error",
					status: 500,
				});
			}
			res.send({
				message: "success",
				status: 200,
			});
		});
	});
});

app.listen(9000, () => {
	console.log("success in 9000");
});
